<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="900px"
    :close-on-click-modal="false"
    @closed="hide"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px" class="combo-form">
      <!-- 套餐基本信息 -->
      <div class="section-title">
        <span>套餐信息</span>
        <el-row class="mt-20">
          <el-col :span="23">
            <el-form-item label="套餐名称" prop="productName">
              <el-input
                v-model="formData.productName"
                placeholder="例如：便秘多宝组合"
                clearable
                maxlength="30"
                show-word-limit
              />
            </el-form-item>
          </el-col>

          <el-col :span="23">
            <el-form-item label="套餐标题" prop="productTitle">
              <el-input
                v-model="formData.productTitle"
                placeholder="例如：便秘克星，三类联合，治疗长久便秘可用"
                clearable
                maxlength="30"
                show-word-limit
              />
            </el-form-item>
          </el-col>

          <el-col :span="23">
            <el-form-item label="套餐规格" prop="productSpec">
              <el-input
                v-model="formData.productSpec"
                placeholder="例如：30包组合装"
                clearable
                maxlength="30"
                show-word-limit
              />
            </el-form-item>
          </el-col>

          <el-col :span="23">
            <el-form-item label="是否固定" prop="isFixed">
              <el-switch
                v-model="formData.isFixed"
                placeholder="例如：100g"
                clearable
                :active-value="1"
                :inactive-value="0"
                show-word-limit
              />
              <div style="color: red; font-size: 12px; margin-left: 5px">
                固定后 选择订单时候 不能修改 数量 金额等
              </div>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="商品图" prop="productImage">
              <ImageUpload
                class="upload-box"
                v-model="formData.productImage"
                action="/common/upload"
                :limit="3"
                :file-type="['png', 'jpg', 'jpeg']"
                :is-show-tip="true"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <!-- 添加商品 -->
      <div class="section-title">
        <span>选择商品</span>
        <div class="section-goods">
          <el-table style="margin-top: 10px" :data="formData.productCollection" border size="small">
            <el-table-column label="产品名称" prop="productName" />
            <el-table-column label="产品详情" prop="productTitle" width="200" />
            <el-table-column label="赠品" prop="isGift" width="60">
              <template #default="{ row }">
                <span>{{ row.isGift === 1 ? '是' : '否' }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="产品类型"
              prop="usageType"
              width="110"
              :formatter="getGoodsTypeByUsageType"
            >
            </el-table-column>
            <el-table-column label="件数" width="150">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.num"
                  @change="recalculateTotals"
                  style="width: 100%"
                  controls-position="right"
                  :min="0"
                />
              </template>
            </el-table-column>
            <el-table-column label="成本价" width="80" prop="costPrice" />
            <el-table-column label="销售价" width="150" prop="salePrice">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.salePrice"
                  @change="recalculateTotals"
                  style="width: 100%"
                  controls-position="right"
                  :min="0"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 价格计算 -->
      <div class="section-title">
        <span>价格与结算</span>
        <el-row class="price-summary">
          <el-col :span="8">
            <div class="summary-item">
              <el-form-item label="商品总价：" label-width="140px">
                <span class="amount highlight">￥{{ totalPrice.toFixed(2) }}</span>
              </el-form-item>
            </div>
            <div class="summary-item">
              <el-form-item label="节省金额：" label-width="140px">
                <span class="amount saving">￥{{ savingAmount.toFixed(2) }}</span>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="14" class="mb-10">
            <div class="summary-item">
              <el-form-item label="套餐优惠价：" prop="salePrice" label-width="110px">
                <el-input-number
                  v-model="formData.salePrice"
                  :min="0"
                  :precision="2"
                  controls-position="right"
                  :step="0.01"
                  style="width: 100%"
                  @change="recalculateSavings"
                >
                  <template #prefix>￥</template>
                </el-input-number>
              </el-form-item>
            </div>
          </el-col>

          <el-col :span="22">
            <el-form-item label="备注：" label-width="140px">
              <el-input
                type="textarea"
                v-model="formData.remark"
                placeholder="可填写套餐描述或注意事项，限200字"
                maxlength="200"
                show-word-limit
                :rows="2"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="hide">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading"> 保存 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, watch, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { addPackage, updateProduct } from '../../api/goods';
import { cloneDeep } from 'lodash';

const props = defineProps({
  goodsList: {
    type: Array,
    default: () => []
  },
  goodsTypes: {
    type: Array,
    default: () => []
  }
});

const emit = defineEmits(['ok']);
// 组件响应
const formRef = ref();
const visible = ref(false);
const submitLoading = ref(false);

const initProduct = () => {
  const newGoodsList = props.goodsList.map((v: any) => {
    v.num = v.num || 0;
    return v;
  });

  formData.productCollection = newGoodsList;
};

const initField = () => ({
  productId: '',
  productName: '',
  productTitle: '',
  productSpec: '',
  productImage: '',
  isFixed: '0', // 是否固定套餐
  salePrice: 0,
  remark: '',
  costPrice: 0,
  externalType: 1,
  type: 1,
  productCollection: [] as any
});

const title = computed(() => {
  return formData.productId ? '编辑套餐' : '创建套餐';
});

// 表单数据
const formData = reactive(initField());

// 监听 goodsList 赋值给 productCollection
watch(
  () => props.goodsList,
  () => {
    initProduct();
  },
  {
    immediate: true,
    deep: true
  }
);
// 实时计算总价
const totalPrice = ref(0);
const savingAmount = ref(0);

const recalculateTotals = () => {
  let costPrice = 0; // 成本价
  let salePrice = 0; // 销售价
  formData.productCollection.forEach((item: any) => {
    if (item.salePrice && item.num) {
      costPrice += item.costPrice * item.num;
      salePrice += item.salePrice * item.num;
    }
  });

  // 成本价
  formData.costPrice = costPrice;
  totalPrice.value = salePrice;

  // 同步节省金额
  recalculateSavings();
};

// 实时计算节省金额
const recalculateSavings = () => {
  if (formData.salePrice !== null && totalPrice.value > 0) {
    savingAmount.value = Math.max(0, totalPrice.value - formData.salePrice);
    formData.salePrice = Math.max(0, totalPrice.value - savingAmount.value);
  } else {
    savingAmount.value = 0;
    formData.salePrice = 0;
  }
};

const checkSalePrice = (_: any, value: any) => value !== null && value >= 0;
const checkTotalPrice = (_: any, value: any) => value <= totalPrice.value;

// 表单验证
const rules = {
  productName: [{ required: true, message: '请输入套餐名称', trigger: 'blur' }],
  productTitle: [{ required: true, message: '请输入套餐标题', trigger: 'blur' }],
  productSpec: [{ required: true, message: '请输入套餐规格', trigger: 'blur' }],
  productImage: [{ required: true, message: '请上传套餐封面', trigger: 'change' }],
  salePrice: [
    { required: true, message: '请输入套餐价格', trigger: 'blur' },
    {
      validator: checkSalePrice,
      message: '套餐价不能为负',
      trigger: 'blur'
    },
    {
      validator: checkTotalPrice,
      message: '套餐价建议不高于商品总价',
      trigger: 'blur'
    }
  ]
};

// 提交
const submitForm = () => {
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) return;

    // 验证至少一个商品
    if (totalPrice.value == 0) {
      ElMessage.warning('请至少添加一个有效商品');
      return;
    }

    const submitDeep = cloneDeep(formData);

    // 套餐优惠价不能为空
    if (submitDeep.salePrice == 0) {
      ElMessage.warning('请输入套餐优惠价');
      return;
    }

    submitLoading.value = true;

    // 清空 formData.productCollection num = 0 得
    submitDeep.productCollection = submitDeep.productCollection.filter((item: any) => item.num > 0);

    // 每个商品也都同步字段 isFixed
    submitDeep.productCollection.forEach((item: any) => {
      item.isFixed = submitDeep.isFixed;
      item.productUnitNum = item.num;
    });

    try {
      let fun;
      // 判断是新增还是修改
      if (submitDeep.productId) {
        // 修改
        fun = updateProduct;
      } else {
        // 新增
        fun = addPackage;
      }

      fun(submitDeep).then((res: any) => {
        if (res.code == 200) {
          ElMessage.success('套餐创建成功！');
          hide();
          emit('ok');
        }
      });
    } catch (e) {
      console.error(e);
      ElMessage.error('创建失败，请稍后重试');
    } finally {
      submitLoading.value = false;
    }
  });
};

// 根据产品类型
const getGoodsTypeByUsageType = (row: any) => {
  const type = row.usageType;
  const findx: any = props.goodsTypes.filter((item: any) => item.value === type);
  if (findx.length > 0) {
    return findx[0].label;
  }
  return '';
};

// 重置表单
const hide = () => {
  visible.value = false;
  formRef.value?.resetFields();
  // 初始化formData
  Object.assign(formData, initField());
  submitLoading.value = false;
};

const show = (data: any) => {
  if (data) {
    // 把 data 中的 productCollection 得 num 转换为 productUnitNum
    // 同步 goodsList  data中的productCollection 数据得 件数 和 销售价 同步到  因为，添加的时候 移除了  为0 得数据
    // 遍历 data.productCollection 中的每个商品 如果没有 直接 push
    // 合并 goodsList 和 data.productCollection，避免重复
    const existingIds = new Set(data.productCollection.map((item: any) => item.productId));
    props.goodsList.forEach((item: any) => {
      if (!existingIds.has(item.productId)) {
        const newItem = { ...item, productUnitNum: 0, num: 0 };
        data.productCollection.push(newItem);
      }
    });
    // 同步数据
    Object.assign(formData, data);
    nextTick(() => {
      recalculateTotals();
    });
  } else {
    initProduct();
  }
  visible.value = true;
};

defineExpose({ show, hide });
</script>

<style scoped lang="scss">
.combo-form {
  :deep(.el-card__header) {
    padding: 12px 16px;
    background-color: #f9f9f9;
    border-bottom: 1px solid #ebeef5;
    font-size: 13px;
    font-weight: 600;
    color: #333;
  }

  .add-production {
    margin: 15px;
    padding: 4px;
    border: 2px dashed #dcdfe6;
    color: #666;
    text-align: center;
    cursor: pointer;
    border-radius: 6px;
    transition: all 0.3s;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      border-color: #409eff;
      color: #409eff;
    }

    div {
      margin-left: 5px;
    }
  }

  .section-title {
    border: 1px solid #ebebeb;
    border-radius: 6px;
    margin-bottom: 16px;
    overflow: hidden;

    & > span {
      display: inline-block;
      padding: 6px 12px;
      background-color: #f5f7fa;
      font-size: 14px;
      font-weight: 500;
      color: #333;
      border-right: 1px solid #ebebeb;
    }
  }

  .section-goods {
    padding: 0 20px 10px 20px;
    box-sizing: border-box;
  }

  .dialog-footer {
    text-align: center;
    padding-top: 10px;
    border-top: 1px dashed #ebeef5;
  }
}

// 自定义上传样式
:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
  border-radius: 8px;
  border: 1px dashed #c0ccda;
  background-color: #fafafa;
}
</style>
